import re
from django import forms
from microerp.apps.customer.models import Customer

'''
定义新建客户表单 ModelForm
'''
class CustomerForm(forms.ModelForm):
    account_name = forms.CharField(max_length=20,error_messages={'required':u'客户名不能为空'})
    phone = forms.CharField(max_length=20,error_messages={'required':u'手机号码不能为空'})
    qq = forms.CharField(required=False)
    qq_nickname = forms.CharField(required=False)
    weixin = forms.CharField(required=False)
    weixin_nickname = forms.CharField(required=False)
    level = forms.IntegerField(required=False)
    notes = forms.CharField(required=False, widget= forms.Textarea(attrs={'cols': 80, 'rows': 20}))
    province = forms.CharField(required=False)
    city = forms.CharField(required=False)
    area = forms.CharField(required=False)
    street = forms.CharField(required=False)

    class Meta:
        model = Customer
        fields= ('account_name', 'phone', 'qq', 'qq_nickname', 'weixin', 'weixin_nickname', 'level', 'notes', 'province', 'city', 'area', 'street')

    def clean(self):
		#获取表单数据
        cleaned_data = self.cleaned_data

        print(cleaned_data.get("account_name"))

        data_phone = cleaned_data.get("phone")
		#验证
        if data_phone:
            pattern = re.compile(r"^((\d{3,4}-)?\d{7,8})$|(1[3-9][0-9]{9})")	#设置正则验证
            if pattern.match(data_phone):	#如果验证失败的话就会返回none
                pass
            else:
                msg = u"请输入正确的机机或座机号码！"
                self._errors["phone"] = self.error_class([msg])	#设置输入框的告警文字
		#传回数据
        return cleaned_data
